package com.ed.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.ed.exception.BaseException;

import java.util.Calendar;
import java.util.Date;

public final class JwtUtil {
	
	public static String createJwt(int userId,String username){
		Calendar instance = Calendar.getInstance();
		// 20秒后令牌token失效
		instance.add(Calendar.HOUR, 2);
		String token = JWT.create()
//			.withHeader(map) // header可以不写，因为默认值就是它
			.withClaim("userId", userId)  //payload
//			.withClaim("username", username)
			.withExpiresAt(instance.getTime()) // 指定令牌的过期时间
			.sign(Algorithm.HMAC256("XIAOSHUANG"));//签名
		return token;
	}
	
	public static Integer parseJwt(String token) {
		// 通过签名生成验证对象
		JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("XIAOSHUANG")).build();
		DecodedJWT verify = jwtVerifier.verify(token);
		// 校验令牌是否过期
		Date expiresAt = verify.getExpiresAt();
		if (expiresAt.before(new Date())) {
			throw new BaseException("登录过期！");
		}
		// 返回登录用户id
		return verify.getClaim("userId").asInt();
  
	}
}
